package jgl.vajra.operator.widget.retrofithelper.rxexception;

import android.os.Environment;
import android.os.SystemClock;
import android.text.TextUtils;

import jgl.vajra.operator.R;
import jgl.vajra.operator.constant.Constant;
import jgl.vajra.operator.manager.AccountManager;
import jgl.vajra.operator.widget.bean.BaseRequestData;
import jgl.vajra.operator.widget.bean.ServerErrorMessageBean;
import jgl.vajra.operator.widget.utils.FileUtils;
import jgl.vajra.operator.widget.utils.ToastUtils;
import jgl.vajra.operator.widget.utils.UIUtils;

import com.orhanobut.logger.Logger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import androidx.annotation.NonNull;


/**
 * Created by Administrator on 2016/11/24 0024.
 */
public class ErrorManager {
    public ErrorManager() {
    }

    /**
     * 对错误数据进行处理，返回对应字符串提示信息
     *
     * @param e 错误数据接口
     * @return 返回对应错误提示信息
     */
    public static ServerErrorMessageBean handleError(ErrorBundle e, boolean isHandlerErrorCode) {
        Exception exception = e.getException();

        exception.printStackTrace();
        ServerErrorMessageBean bean = new ServerErrorMessageBean();
        String message = "";


        if (exception instanceof HttpNativeException) {
            HttpNativeException httpNativeException = (HttpNativeException) exception;
            BaseRequestData netData = httpNativeException.getNetData();
            if (netData == null) {
                message = UIUtils.getString(R.string.service_error);
                bean.code = Constant.ERROR_CODE_NORMAL;
            } else {
                handleSeverError(netData.code);
                message = getErrorFromString(netData);
                bean.code = netData.code;
            }
        } else if (exception instanceof IOException || exception instanceof NetworkConnectionException) {
            message = UIUtils.getString(R.string.network_error);
        } else if (exception instanceof ServerException) {
            int code = ((ServerException) exception).getCode();
            //在这里可以获取code来判断是什么类型，进行相应处理，比如token失效了可以实现跳转到登录页面
            // message = e.getMessage();
            message = ((ServerException) exception).getMessage();
            bean.code = code;
            Logger.d("ErrorManager +thread" + Thread.currentThread().getName());
            if (bean.code == 1001) {
                isHandlerErrorCode = false;
                AccountManager.getInstance().logout(UIUtils.getContext());
                AccountManager.getInstance().toDialogLoginHomeActivity();
            } else {
                handleSeverError(code);

            }
        } else {
            message = UIUtils.getString(R.string.service_error);
            //saveErrorToFile(bean, 2);
        }
        if (bean.code == 1001) {
            bean.message = "网络异常 请重试";
        } else {
            bean.message = message;
        }
        if (bean.code != 1001 && isHandlerErrorCode) {
            ToastUtils.showShort(bean.message);
        }


        return bean;
    }

    private static void saveErrorToFile(ServerErrorMessageBean bean, int type) {
        String fileName = "net-" + SystemClock.currentThreadTimeMillis() + ".txt";
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            File dir = FileUtils.getExceptionFolderFile();
            String path = dir.getPath();
            if (!dir.exists()) {
                // 创建此抽象路径名指定的目录，包括所有必需但不存在的父目录。
                dir.mkdirs();
            }
            File exFile = new File(dir, fileName);
            if (!exFile.exists()) {
                try {
                    exFile.createNewFile();
                    FileOutputStream fos = new FileOutputStream(exFile);
                    String message = "type=" + type + "message=" + bean.message + "status=" + bean.code;
                    fos.write(message.getBytes());
                    // 发送给开发人员
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    }


    @NonNull
    private static String getErrorFromString(BaseRequestData netData) {
        String message;
        message = UIUtils.getIdentifierErrorCode("code_" + netData.code);
        if (TextUtils.isEmpty(message)) {
            if (TextUtils.isEmpty(netData.msg)) {
                message = UIUtils.getString(R.string.code_1000);
            } else {
                message = netData.msg;
            }
        }
        return message;
    }

    @NonNull
    private static String getErrorFromString(int netData) {
        String message;
        message = UIUtils.getIdentifierErrorCode("code_" + netData);
        if (TextUtils.isEmpty(message)) {
            message = UIUtils.getString(R.string.code_1000);
        }
        return message;
    }

    public static void showErrorFromStringToast(int netData) {
        ToastUtils.showShort(getErrorFromString(netData));
    }

    public static ServerErrorMessageBean handleError(ErrorBundle e) {
        return handleError(e, true);
    }

    private static void handleSeverError(int netData) {
        switch (netData) {
            case 1002:
                // accessToken 过期 刷新token
                AccountManager.getInstance().refreshToken(UIUtils.getContext());
                break;
            case 1006:
                // refresh accessToken 过期
                //  IntentController.toLoginActivity(AppActivityManager.getAppActivityManager().currentActivity());
                break;
        }
    }
}
